package com.flashlightonoff;

import com.flashlightonoff.R;

import android.os.Bundle;
import android.app.Activity;
import android.content.pm.PackageManager;
import android.view.Menu;
import android.widget.ImageView;
import android.widget.Toast;
import android.view.View;
import android.hardware.Camera;
import android.hardware.Camera.Parameters;
import android.content.pm.ActivityInfo;

public class MainActivity extends Activity implements View.OnClickListener {

	private boolean _isFlashOn = false;
	private Camera _cam;
	private ImageView _imageButton;
	private boolean _isFlashAvailable = false;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
		
		_isFlashAvailable = this.getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH);
		_imageButton = (ImageView)findViewById(R.id.imageButton);
		_imageButton.setOnClickListener(this);
		
		if (!_isFlashAvailable){
			showMsgNoFlash();
		} else {
			turnOnOffFlash();
		}
	}
	
	private void showMsgNoFlash(){
		Toast.makeText(this, getString(R.string.msg_no_flash), Toast.LENGTH_LONG).show();
	}
	
	private void turnOnOffFlash(){
		if (_isFlashOn) {
			_cam.stopPreview();
			_cam.release();
			_isFlashOn = false;
			_imageButton.setImageResource(R.drawable.button_off);
		} else {
		    _cam = Camera.open();
		    Parameters p = _cam.getParameters();
		    p.setFlashMode(Parameters.FLASH_MODE_TORCH);
		    _cam.setParameters(p);
		    _cam.startPreview();
		    _isFlashOn = true;
			_imageButton.setImageResource(R.drawable.button_on);
		}
		
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		//getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}
	
	@Override
	public void onBackPressed(){
		if (_isFlashOn) {
			turnOnOffFlash();
		}
		finish();
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.imageButton:
			if (!_isFlashAvailable){
				showMsgNoFlash();
			}else{
				turnOnOffFlash();
			}
			break;

		default:
			break;
		}
		
	}

}
